package com.liferay.portal.events;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.LayoutSet;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.shopping.model.ShoppingCart;
import com.liferay.portlet.shopping.service.ShoppingCartLocalServiceUtil;
import com.slayer.model.CartItem;
import com.slayer.model.ShoppingCartExt;
import com.slayer.service.ShoppingCartExtLocalServiceUtil;
import com.util.CartUtil;

public class UserCartSyncAction extends Action {
	/* (non-Java-doc)
	 * @see com.liferay.portal.kernel.events.Action#Action()
	 */
	/*public UserCartSyncAction() {
		super();
	}
	 */
	/* (non-Java-doc)
	 * @see com.liferay.portal.kernel.events.Action#run(HttpServletRequest arg0, HttpServletResponse arg1)
	 */
	public void run(HttpServletRequest request, HttpServletResponse response)  {
		// TODO Auto-generated method stub
		
		HttpSession session = request.getSession();
		
		LayoutSet layoutSet = (LayoutSet)request.getAttribute("VIRTUAL_HOST_LAYOUT_SET");
		User user = null;
	    try {
            user = PortalUtil.getUser(request);
        } catch (PortalException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SystemException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
		long groupId = layoutSet.getGroupId();
		ShoppingCart shoppingCart = CartUtil.getCart(user, groupId);
	
		if (Validator.isNull(shoppingCart))	return; 
		
		String currentItems = shoppingCart.getItemIds();
		
		if (Validator.isNotNull(currentItems)) {
			currentItems += StringPool.COMMA;
		}
		
		@SuppressWarnings("unchecked")
		Map<Long, CartItem> items = (Map<Long, CartItem>) session.getAttribute("USER_CART_ITEMS");
		
		if (items != null && items.size() > 0) {
			Iterator<Long> itr = items.keySet().iterator();
			
			while (itr.hasNext()) {
				long itemId = itr.next();
				CartItem item = items.get(itemId);
				ShoppingCartExtLocalServiceUtil.persistCartExt(itemId, shoppingCart.getCartId(), item);

			}
			shoppingCart.setModifiedDate(new java.util.Date());
			
			try {
				ShoppingCartLocalServiceUtil.updateShoppingCart(shoppingCart);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		
		// re-initialize the session object
		syncCartItemsFromDB(session, shoppingCart);

	}

	private void syncCartItemsFromDB(HttpSession session,
			ShoppingCart shoppingCart) {
		// TODO Auto-generated method stub
		
		Map<Long, CartItem> items = new HashMap<Long, CartItem>();
		session.setAttribute("USER_CART_ITEMS", items);
		
		long cartId = shoppingCart.getCartId();
		
		try {
			List<ShoppingCartExt> shoppingCartExtList = ShoppingCartExtLocalServiceUtil.getByCartId(cartId);
			
			for (ShoppingCartExt shoppingCartExt: shoppingCartExtList) {
				CartItem cartItem = new CartItem(
						shoppingCartExt.getQty(), 
						shoppingCartExt.getAmount(),
						shoppingCartExt.getFrequency());
				
				items.put(shoppingCartExt.getItemId(), cartItem);
			}
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}